<?php

namespace app\stock\controller;

use think\Controller;
use think\Request;

class Admin extends Controller
{
    protected $AdminModel = null;

    function __construct()
    {
        parent::__construct();

        $this->AdminModel = model('admin.Admin');
    }

    // 微信登录
    public function wxlogin()
    {
        $code = $this->request->param('code', '', 'trim');

        if (!$code) {
            $this->error("获取临时登录凭证失败!");
        }

        $res = $this->code2Session($code);

        if ($res['code'] == 0) {
            $this->error($res['msg']);
        }

        $openid = $res['data']['openid'] ?? '';

        if (!$openid) {
            $this->error('授权失败!');
        }

        $admin = $this->AdminModel->where(['openid' => $openid])->find();

        if (!$admin) {
            $this->error('请先绑定账号', null, ['action' => 'bind', 'openid' => $openid]);
        }

        if ($admin['status'] !== 'normal') {
            $this->error('账号已禁用');
        }

        // 登录管理员信息返回前端
        $data = [
            'id' => $admin['id'],
            'username' => $admin['username'],
            'nickname' => $admin['nickname'],
            'avatar_cdn' => $admin['avatar_cdn'],
            'email' => $admin['email'],
            'mobile' => $admin['mobile'],
            'group_text' => $admin['group_text'],
            'createtime' => $admin['createtime']
        ];

        $this->success('登录成功', null, $data);
    }

    // 绑定账号
    public function bind()
    {
        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');

        $admin = $this->AdminModel->where(['username' => $username])->find();

        if (!$admin) {
            $this->error('所绑定的账号不存在!');
        }

        $password = md5(md5($password) . $admin['salt']);
        if ($password !== $admin['password']) {
            $this->error('密码输入错误!');
        }

        if ($admin['status'] !== 'normal') {
            $this->error('账号被禁用!');
        }

        if (empty($openid)) {
            $this->error('登录凭证不存在');
        }

        $data = [
            'id' => $admin['id'],
            'openid' => $openid
        ];

        $result = $this->AdminModel->isUpdate(true)->save($data);

        if ($result) {
            $this->success('账号绑定成功!');
        } else {
            $this->error("账号绑定失败!");
        }

    }

    // 解除微信绑定
    public function unbinding()
    {
        $id = $this->request->param('id', 0, 'trim');
        $admin = $this->AdminModel->find($id);

        if (!$admin) {
            $this->error('该账号不存在!');
        }

        $data = [
            'id' => $id,
            'openid' => null
        ];

        $result = $this->AdminModel->isUpdate(true)->save($data);

        if ($result === 1) {
            $this->success('解绑成功!');
        } else {
            $this->error('解绑失败!');
        }
    }

    // 图片上传
    public function upload()
    {
        $id = $this->request->param('id', '', 'trim');
        // 接收上传图片信息
        $file = $this->request->file('avatar');

        $admin = $this->AdminModel->find($id);

        if (!$admin) {
            $this->error('该管理员不存在!');
        }

        $avatarRes = build_upload('avatar');

        if ($avatarRes['code'] === 0) {
            $this->error($avatarRes['msg']);
        }

        $data = [
            'id' => $id,
            'avatar' => $avatarRes['data']
        ];

        $result = $this->AdminModel->isUpdate(true)->save($data);

        if ($result === false) {
            if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                @is_file(ltrim($data['avatar'], '/')) && @unlink(ltrim($data['avatar'], '/'));
            }

            $this->error('更新头像失败');
        } else {
            if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                @is_file(ltrim($admin['avatar'], '/')) && @unlink(ltrim($admin['avatar'], '/'));
            }

            $admin = $this->AdminModel->find($id);

            $data = [
                'id' => $admin['id'],
                'username' => $admin['username'],
                'nickname' => $admin['nickname'],
                'avatar_cdn' => $admin['avatar_cdn'],
                'email' => $admin['email'],
                'mobile' => $admin['mobile'],
                'group_text' => $admin['group_text'],
                'createtime' => $admin['createtime']
            ];

            $this->success('更新头像成功', null, $data);
        }

    }

    // 修改资料
    public function profile()
    {
        $params = $this->request->param();
        $admin = $this->AdminModel->find($params['id']);

        if (!$admin) {
            $this->error('该用户不存在!');
        }

        $data = [
            'id' => $params['id'],
            'nickname' => $params['nickname'],
            'mobile' => $params['mobile'],
            'email' => $params['email']
        ];

        if (isset($params['password'])) {
            $repass = md5(md5($params['password']) . $admin['salt']);
            if ($repass === $admin['password']) {
                $this->error('新密码不能与原密码一致!');
            }
            $salt = mt_rand();
            $password = md5(md5($params['password']) . $salt);
            $data['password'] = $password;
            $data['salt'] = $salt;
        }

        $result = $this->AdminModel->isUpdate(true)->save($data);

        if ($result === false) {
            $this->error('更新资料失败!');
        } else {
            $admin = $this->AdminModel->find($params['id']);

            $data = [
                'id' => $admin['id'],
                'username' => $admin['username'],
                'nickname' => $admin['nickname'],
                'avatar_cdn' => $admin['avatar_cdn'],
                'email' => $admin['email'],
                'mobile' => $admin['mobile'],
                'group_text' => $admin['group_text'],
                'createtime' => $admin['createtime']
            ];

            $this->success('更新资料成功', null, $data);

        }
    }

    public function login()
    {
        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');

        $admin = $this->AdminModel->where(['username' => $username])->find();

        if (!$admin) {
            $this->error('用户名不存在!');
        }

        $password = md5(md5($password) . $admin['salt']);

        if ($password !== $admin['password']) {
            $this->error('密码错误!');
        }

        if ($admin['status'] !== 'normal') {
            $this->error('账号已禁用!');
        }

        // 登录管理员信息返回前端
        $data = [
            'id' => $admin['id'],
            'username' => $admin['username'],
            'nickname' => $admin['nickname'],
            'avatar_cdn' => $admin['avatar_cdn'],
            'email' => $admin['email'],
            'mobile' => $admin['mobile'],
            'group_text' => $admin['group_text'],
            'createtime' => $admin['createtime']
        ];

        $this->success('登录成功', null, $data);
    }

    // 获取登录用户的openid的方法
    private function code2Session($code)
    {
        // 定义返回结果数组
        $result = [
            'code' => 0,
            'msg' => '登录凭证未知',
            'data' => null,
        ];

        // 如果code是存在就开始请求
        if ($code) {
            // 小程序appid(改成自己的)
            $appid = 'wxfd705378ecfec837';

            // 小程序密钥(改成自己的)
            $AppSecret = '79b375a782d5a7e9801b6f7b8120443e';

            // 请求地址
            $apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$AppSecret&js_code=$code&grant_type=authorization_code";

            $res = httpRequest($apiUrl);

            // 由于接口返回的数据是json数据包，转成数组
            $res = json_decode($res, true);

            $result = [
                'code' => 1,
                'msg' => '获取登录凭证成功',
                'data' => $res
            ];

            return $result;
        }

        return $result;
    }


}